# coding=utf-8

import os
import requests
from django.conf import settings
from django.utils import timezone
from django.utils.deconstruct import deconstructible


def UploadFile(file, upload_path):
    upload_path = PathAndRename(upload_path)
    filename = "%s%s.%s" % (
        upload_path.path,
        timezone.now().strftime('%Y%m%d%H%M%S%f'),
        file.name.split('.')[-1]
    )
    filename = filename.lower()
    full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
    with open(full_filename, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    return filename


def DownloadFace(url, save_path, ext):
    upload_path = PathAndRename(save_path)
    filename = "%s%s.%s" % (
        upload_path.path,
        timezone.now().strftime('%Y%m%d%H%M%S%f'),
        ext
    )
    filename = filename.lower()
    full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
    response = requests.get(url)
    img = response.content
    with open(full_filename, 'wb+') as destination:
        destination.write(img)
    return filename


def DeleteFile(filename):
    img_path = '%s/%s' % (settings.MEDIA_ROOT, filename)
    try:
        if os.path.exists(img_path):
            os.remove(img_path)
    except:
        pass


@deconstructible
class PathAndRename(object):

    def __init__(self, sub_path):
        self.path = sub_path

        self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
        if not os.path.exists(self.full_path):
            os.makedirs(self.full_path)

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        t = timezone.now().strftime('%Y%m%d%H%M%S%f')

        if instance.pk:
            filename = '{}-{}.{}'.format(instance.pk, t, ext)
        else:
            filename = '{}.{}'.format(t, ext)
        return os.path.join(self.path, filename)


@deconstructible
class CertPath(object):

    def __init__(self, sub_path):
        self.path = sub_path

        self.full_path = "%s/%s" % (settings.MEDIA_ROOT, sub_path)
        if not os.path.exists(self.full_path):
            os.makedirs(self.full_path)

    def __call__(self, instance, filename):
        return os.path.join(self.path, filename)
